package com.zhidian.edm.util;

import org.springframework.beans.BeanUtils;
import java.util.*;
import java.util.stream.Collectors;

public class BeanConvertUtil {

    /**
     * 转换列表，只能转换相同属性
     * @param sourceList
     * @param targetClass
     * @return
     * @param <S>
     * @param <T>
     */
    public static <S, T> List<T> convertList(List<S> sourceList, Class<T> targetClass) {
        if (sourceList == null || sourceList.isEmpty()) {
            return List.of();
        }

        return sourceList.stream()
                .map(source -> convert(source, targetClass))
                .collect(Collectors.toList());
    }

    /**
     * 单个对象转换（使用 BeanUtils，只能住哪换相同属性）
     */
    public static <S, T> T convert(S source, Class<T> targetClass) {
        if (source == null) {
            return null;
        }

        try {
            T target = targetClass.getDeclaredConstructor().newInstance();
            BeanUtils.copyProperties(source, target);
            return target;
        } catch (Exception e) {
            throw new RuntimeException("对象转换失败", e);
        }
    }

    public static <S, T> T copyProperties(S source, T target) {
        if (source == null || target == null) {
            return target; // 若源或目标为null，直接返回目标对象（避免空指针）
        }

        BeanUtils.copyProperties(source, target);
        return target;
    }
}
